package com.jiayuge.server.config.websocket;

import com.jiayuge.server.config.security.component.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 功能: WebSocket配置类
 *
 * @Program: yeb
 * @Date: 2021-12-08 09:57
 * @Author Jiayu.Yang
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    /*
    添加端点Endpoints，这样在网页可以通过websocket连接上服务
        也就是配置websocket的服务地址，并指定是否使用socketJS
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        /**
         * 1、将/ws/ep路劲组测为stomp的端点，用户链接这个端点就可以进行websocket通讯，支持socketJS
         * 2、setAllowedOrigins("*")：所有请求允许跨域
         * 3、withSockJS：支持socketJS访问
         */
        registry.addEndpoint("/ws/ep").setAllowedOrigins("*").withSockJS();
    }

    /*
    使用JWT令牌的时候，才需要配置
    获取JWT令牌配置输入通道参数配置
     */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            //消息预发送的做的相应处理
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                //获取访问器
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                //判断是否为链接，如果是，需要获取token，并设置用户对象
                if (StompCommand.CONNECT.equals(accessor.getCommand())){
                    //根据前端请求获取token
                    //Auth-Token 是客户端发送的key
                    String token = accessor.getFirstNativeHeader("Auth-Token");
                    //如果token存在
                    if (!StringUtils.isEmpty(token)){
                        //截取有验证意义的token（完整的令牌）
                        String authToken = token.substring(tokenHead.length());
                        //从token中获取用户名
                        String username = jwtTokenUtil.getUserNameFromToken(authToken);
                        //如果用户名存在
                        if (!StringUtils.isEmpty(username)){
                            //登录
                            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                            //验证token是否有效，有效就重新设置用户对象
                            if (jwtTokenUtil.validateToken(authToken,userDetails)){
                                //重新设置用户对象，（校验条件）
                                UsernamePasswordAuthenticationToken authenticationToken =
                                        new UsernamePasswordAuthenticationToken(userDetails, null,
                                                userDetails.getAuthorities());
                                //添加到Security全局配置中
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                                //添加到访问器器
                                accessor.setUser(authenticationToken);
                            }
                        }
                    }
                }
                return message;
            }
        });

    }

    /*
    配置消息代理
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //配置代理域，可以配置多个(配置代理目的地前缀为/queue，可以在配置域上向客户端推送消息)
       registry.enableSimpleBroker("/queue");
    }
}
